package com.qdu.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.qdu.entity.Job;
import com.qdu.entity.Usert;
import com.qdu.service.ManagerService;
import com.qdu.service.SocketService;
import com.qdu.service.UsertService;
import com.qdu.util.DateUtil;
import com.qdu.util.SendmailUtil;

@Controller
@CrossOrigin
@RequestMapping("/usert")

public class UsertController {
	
	private static final String String = null;

	@Autowired
	UsertService us;
	
	@Autowired
	ManagerService ms;
	
	@Autowired
	SocketService s;

	
	@Autowired
	UserDetailsService userDs;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@GetMapping("/ifhasEmail")
	@ResponseBody
	public String ifhas(String uemail) {
		int count = us.ifHasemail(uemail);
		if(count==0)
			return "邮箱不存在，请重新输入";
		return "";
	}
	
	@PostMapping("/userD")//个人空间页面获取用户信息
	@ResponseBody
	public Usert getUser(String uid) {
		return us.findUserbyuid(uid);
	}
	
	//跳转到addUsert.html页面
    @PostMapping("/getAll")
    @ResponseBody
    public List<Usert> getAllUsert() {
        return us.getAll();
    }  
    
    @PostMapping("/getid")
    @ResponseBody
    public String getid(HttpSession session) {
        if(session.getAttribute("id")==null||session.getAttribute("id").equals("")) {
        	return "1";
        }
        else {
        	return (String)session.getAttribute("id");
        }
    }  
    
	@PostMapping("/islogin")
	@ResponseBody
	public boolean islogin(HttpSession session) {
		if(session.getAttribute("islogin")==null) {
			return false;
		}
		if(session.getAttribute("islogin").equals(true)) {
			return true;
		}
		if(session.getAttribute("islogin").equals(false)) {
			return false;
		}
		return false;
	    }  
	@PostMapping("/getloginid")
	@ResponseBody
	public String getlogin(HttpSession session) {
		if(session.getAttribute("id")!=null)
			return session.getAttribute("id").toString();
		return "游客您好";

	    }  
	//注册用户
	@PostMapping("/addUsert")
	@ResponseBody
	public Usert insertUsert(@RequestParam MultipartFile uimg,@RequestParam Map<String,Object> map)  throws IllegalStateException, IOException{
		//String uid,String upwd,String ugender,String uemail,String uphone,String uinterest,MultipartFile uimg,int ulevel
		//File uimg = new File((String)map.get("uimg"));
		System.out.println("......................................");
		System.out.println("文件原名称：" + uimg.getName());
		String oldName=uimg.getOriginalFilename();
		//这里调用UUID类的静态方法randomUUID()生成一个UUID值作为文件新名称
		//去掉其中的中划线，并且连接上文件的扩展名
		String newName=UUID.randomUUID().toString().replace("-","")
				       +oldName.substring(oldName.lastIndexOf("."));
		
		System.out.println("文件新名称："+newName); 
		String today=DateUtil.getToday();
		//获取/static/img的真实路径
		String realPath=new String("src/main/resources/static/uimg");//ResourceUtils.getURL("classpath:static/static/uimg").getPath();
		System.out.println("/static/img的真实路径："+realPath);

		
		File folder=new File(realPath+"/"+today);
		if(!folder.exists()) //如果文件夹不存在，则创建文件夹，如果存在，不重复创建
			folder.mkdirs(); //创建文件夹
		
		//调用transferTo()方法将接受的文件转移到指定文件
		//这里需要用一个File对象指定文件所在目录和文件名
		uimg.transferTo(new File(folder,newName));
		
		//将新用户的密码进行加密
		String encryptedPassword=passwordEncoder.encode((String)map.get("upwd"));
		
	//	model.addAttribute("msg", "上传成功！");
		//将文件路径返回给页面，用于显示上传的文件，这里是图片（可以上传任何类型文件）
	//	model.addAttribute("imgPath", today+"/"+newName);
		String imgPath = new String("uimg/"+today+"/"+newName);
		Usert user = new Usert();
		user.setUid((String)map.get("uid"));
		user.setUpwd(encryptedPassword);
		user.setUgender((String)map.get("ugender"));
		user.setUemail((String)map.get("uemail"));
		user.setUphone((String)map.get("uphone"));
		user.setUinterest((String)map.get("uinterest"));
		user.setUimg(imgPath);
		//user.setUlevel(Integer.parseInt((String)map.get("ulevel")));
		user.setUpasswordexpre((String)map.get("upasswordexpre"));
		user.setUpasswordanswer((String)map.get("upasswordanswer"));
		us.addUsert(user);
		System.out.println(imgPath);
		WebSocket.SendMessage(s.getAllData("有新用户注册"));
		return user;
	}
	
	
	//修改用户信息
	@PostMapping("/editUsert")
	@ResponseBody
	public Usert editUsert(@RequestParam(required = false) MultipartFile uimg,@RequestParam Map<String,Object> map) throws IllegalStateException, IOException{
		Usert user = new Usert();
		if(uimg != null) {
		System.out.println("......................................");
		System.out.println("文件原名称：" + uimg.getName());
		String oldName=uimg.getOriginalFilename();
		//这里调用UUID类的静态方法randomUUID()生成一个UUID值作为文件新名称
		//去掉其中的中划线，并且连接上文件的扩展名
		String newName=UUID.randomUUID().toString().replace("-","")
				       +oldName.substring(oldName.lastIndexOf("."));
		
		System.out.println("文件新名称："+newName); 
		
		//获取/static/img的真实路径
		String realPath=new String("src/main/resources/static/uimg");
		System.out.println("/static/img的真实路径："+realPath);

		String today=DateUtil.getToday();
		File folder=new File(realPath+"/"+today);
		if(!folder.exists()) //如果文件夹不存在，则创建文件夹，如果存在，不重复创建
			folder.mkdirs(); //创建文件夹
		
		//调用transferTo()方法将接受的文件转移到指定文件
		//这里需要用一个File对象指定文件所在目录和文件名
		uimg.transferTo(new File(folder,newName));
		String imgPath = new String("uimg/"+today+"/"+newName);
		user.setUimg(imgPath);
		}
		else {
			user.setUimg((String)map.get("uimg1"));
		}
	//	String encryptedPassword=passwordEncoder.encode((String)map.get("upwd"));
		
		user.setUid((String)map.get("uid"));       //uid在html页面上设置为可读
		//user.setUpwd(encryptedPassword);
		user.setUgender((String)map.get("ugender"));
		user.setUemail((String)map.get("uemail"));
		user.setUphone((String)map.get("uphone"));
		user.setUinterest((String)map.get("uinterest"));
		
		us.updateUsert(user);
		return user;
	}
	
	//通过昵称获取密保问题
	@PostMapping("/getMibao")
	@ResponseBody
	public String getMibao(String uid) {
		String mibao = us.findUserbyuid(uid).getUpasswordexpre();   
		return mibao;   //改，将密保问题添加至UsertfindPwd.html
		
	}
	//
	
	//通过密保问题答案找回密码
	@PostMapping("/findUpwdBymibao")
	@ResponseBody
	public String findUpwdBymibao(@RequestParam("uid") String uid,@RequestParam("upasswordexpre") String upasswordexpre,@RequestParam("upasswordanswer")String upasswordanswer) {
		Usert u = us.findUsertPwdBymibao(uid,upasswordexpre, upasswordanswer);
		if(u!=null) {
			return u.getUemail(); //这里直接跳转到设置新密码页面
		}else {
			return "500";
		}
	}
	
	//跳转到UsertfindPwdbyEmail.html页面
    @GetMapping("/to_UsertfindPwdbyEmail")
    public String toUsertFindPwdbyEmail() {
        return "UsertfindPwdbyEmail";
    }  
    //跳转到UsertfindPwdbyEmail.html页面
    @GetMapping("/usert/to_mibao")
    public String toUsertFindPwdbymibao() {
    	return "UsertfindPwdbyMibao";
    }  
    
	//通过用户邮箱重设密码
	@RequestMapping("/findUpwdByUemail")
    @ResponseBody
    public Map forgetPass(HttpServletRequest request,@RequestParam("uemail") String uemail){
    	Usert user = us.findUsertPwdByEmail(uemail);   
    	System.out.println(user);
        Map<String, String> map = new HashMap<String ,String >();
        String msg = "";
        if(uemail.equals("")){              //用户名不存在
            msg = "请输入用户名或邮箱！";
          map.put("msg",msg);
            return map;
        }
        if(user == null){              //用户不存在
            msg = "用户名不存在,你不会忘记用户名了吧?";
          map.put("msg",msg);
            return map;
        }
        try{
            String secretKey= UUID.randomUUID().toString();  //密钥
            long time = System.currentTimeMillis()+30*60*1000;
            long date = time/1000*1000;                  //忽略毫秒数
            Timestamp outDate = new Timestamp(date);//30分钟后过期
            user.setValidatacode(secretKey);
            user.setOutdate(outDate);
            us.updateUsert(user);                        //us.updateXtYh(xtYh); //修改密码保存到数据库
            String key = user.getUemail()+"$"+date+"$"+secretKey;
            //String digitalSignature = Md5.MD5Encode(key);                 //数字签名
            //String digitalSignature = passwordEncoder.encode(key);
            String digitalSignature = user.getUid();
            System.out.println(digitalSignature);
            
            String emailTitle = "密码找回";
            String path = request.getContextPath();
            String localstr=request.getLocalAddr();
            System.out.println(localstr);
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            String resetPassHref =  basePath+"usert/user/resetpassword?uid="+URLEncoder.encode(digitalSignature,"UTF-8")+"&uemail="+user.getUemail();
            String emailContent = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href="+ resetPassHref +
            "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'"+"<br/>tips:本链接可能被邮箱拦截，如链接无效，请复制下列链接到您的浏览器中。<br/>"+
    		"链接开始：<span style='color:#F00; font-weight:bold'>"+resetPassHref+"<span>链接结束";
   
            SendmailUtil.class.newInstance().doSendHtmlEmail(emailTitle,emailContent,user.getUemail());//调用工具类里面的发送发放
            msg = "操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码";
        		}catch (Exception e){
        			e.printStackTrace();
        			msg="邮箱不存在？";
        		}
        			map.put("msg",msg);
        			return map;
			}
	
	
	//点击邮箱中发送的链接
	//前三个if return到带msg的错误页面!!!!!!!!
	@GetMapping(value = "/user/resetpassword")
	//@ResponseBody
    public String checkResetLink(@RequestParam("uid") String uid,@RequestParam(value = "uemail")String uemail,Model model) throws UnsupportedEncodingException{
       	System.out.println(uid+uemail);
        String msg = "";
        if(uid.equals("") || uemail.equals("")){
            msg="链接不完整,请重新生成";
            model.addAttribute("msg",msg);
            return msg;
        }
        
        Usert user = us.findUsertPwdByEmail(uemail);
        System.out.println(user);
        if(user == null){
            msg = "链接错误,无法找到匹配用户,请重新申请找回密码.";
           model.addAttribute("msg",msg) ;
            return msg;
        }
        Date outDate = user.getOutdate();
        Date now = new Date();
        System.out.println(outDate.getTime());
        System.out.println(System.currentTimeMillis());
        if(outDate.getTime() <= System.currentTimeMillis()){         //表示已经过期
            msg = "链接已经过期,请重新申请找回密码.";
           model.addAttribute("msg",msg) ;
            return msg;
        }
        String key = user.getUemail()+"$"+outDate.getTime()/1000*1000+"$"+user.getValidatacode();          //数字签名
        String digitalSignature = user.getUid();
        //String digitalSignature = passwordEncoder.encode(key);
        //String digitalSignature = Md5.MD5Encode(key);
        
        System.out.println("……………………………………"+uid);
        System.out.println("……………………………………"+digitalSignature);
        System.out.println(key+"\t"+digitalSignature);
        if(!digitalSignature.equals(uid)) {
            msg = "链接不正确,是否已经过期了?重新申请吧";
           model.addAttribute("msg",msg);
            return msg;
        }
        msg = "邮箱验证成功，请重置密码！";
        model.addAttribute("msg", msg);
        model.addAttribute("uemail",uemail);
        model.addAttribute("uid", uid);
        return "resetUpwd";
    }
	
	//修改密码页面
	@Transactional
	@PostMapping("/modifyUpwd")
	@ResponseBody
	public String modifyUpwd(@RequestParam Map<String,Object> map,HttpSession session) {
		
		String encryptedPassword=passwordEncoder.encode((String)map.get("upwd"));
		Usert user = new Usert();
		user.setUid((String)map.get("uid"));
		user.setUpwd(encryptedPassword);
		us.updateUpwd(user);
		ms.updateRolepwd(encryptedPassword, (String)map.get("uid"));
		session.invalidate();
		return "修改成功！";   //这里修改为直接跳转到登陆页面重新登陆
	}

	

	
	//跳转到usertlogin.html页面
    @GetMapping("/to_usertlogin")
    public String toUsertLogin() {
        return "ulogin";
    }  
    //跳转到usertlogin.html页面
    @PostMapping("/usert/to_search")
    public String tosearch() {
    	return "SearchPage";
    }  

	
	//用户登录
	@PostMapping("/usertlogin")
	@ResponseBody
	public String userlogin(HttpSession session,@RequestParam("username")String uid,@RequestParam("password")String upwd) {
		Usert user = us.findUserbyuid(uid);
		UserDetails userD = userDs.loadUserByUsername(uid);
		BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
		if(bc.matches(upwd, user.getUpwd())) {
			session.setAttribute(userD.getUsername(), user);//以用户名为属性名能唯一区分Session中的用户
			return userD.getUsername();
		}else {
		return "登陆失败";
		}
	}
	
	//用户登出
	@RequestMapping("/userLogout")
	@ResponseBody
	public String logout(HttpSession session) {
		session.invalidate();
		return "用户已登出！";
	}
	
	
//	@RequestMapping("/findJobs")
//	@ResponseBody
//	public List<Job> getJob(@RequestParam Map<String,Object> map) {
//		String jobname1 = (String)map.get("jobname");
//		String jobname = new String(jobname1);
//		List<Job> list =us.queryJobByjobName(jobname);
//		return list;
//	}
	
	@PostMapping("/findJob")
	@ResponseBody
    public List<Map<String,Object>> findStudents(@RequestParam(value = "jobname",required = false)String jobname,
    		@RequestParam(value = "bname",required = false) String bname) {
     return us.queryJobByjobName(jobname,bname);
    }
	
	
	//用户下载平台提供的简历模板，需要登录才可进行该操作
	@RequestMapping("/downloadresume")
	public ResponseEntity<byte[]> download() throws IOException {
		
		String realPath="C:/download/简历模板.doc";
		byte[] data=FileUtils.readFileToByteArray(new File(realPath));
		
		HttpHeaders headers=new HttpHeaders();
		headers.add("content-disposition", "attachment;filename=resume.doc");
		
		ResponseEntity<byte[]> responseEntity
		=new ResponseEntity<byte[]>(data,headers,HttpStatus.OK);
		
		return responseEntity;
	}
	
	//注册时获取职业兴趣
	@PostMapping("/interest")
	@ResponseBody
	public List<Map<String,String>> interestList(){
		List<String> list = us.getInterestList();
		List<Map<String,String>> interestList = new ArrayList<>();
		for(int i = 0;i<list.size();i++) {
			String name = "interest";
			String value  = list.get(i);
			Map<String,String> temp  = new HashMap<>();
			temp.put(name, value);
			interestList.add(temp);
		}
		System.out.print(list.size());
	
		return interestList;
	}
	
	@RequestMapping("/getProcess")
	public BigInteger getProcess(String uid) {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		uid=(String) request.getSession().getAttribute(uid);
		BigInteger state=(BigInteger)us.getProcess(uid);
		//String string = (String) request.getSession().getAttribute("randomCode");
		System.out.println(state);
		return state;
	}


	
	@PostMapping("/isuid")
	@ResponseBody
	public int isuidExist(@RequestParam String uid) {
		boolean isuidExist = us.isuidExist(uid);
		if(isuidExist) {//用户名重复
			return 400;
		}
		return 200;
	}
	@PostMapping("/updateResume")
	@ResponseBody
	public String updateResumeFile(@RequestParam("uid")String uid, @RequestParam("jid")String jid, MultipartFile pfile,HttpServletRequest request) {
		HashMap<String, Object> result=new HashMap<>();
		String url="";
//		uid=(String) request.getSession().getAttribute(uid);
//		jid=(String) request.getSession().getAttribute(jid);
		System.out.println("您的ID：" + uid);
		System.out.println("申请职业：" + jid);
		String oldName=pfile.getOriginalFilename();
//		String newName=UUID.randomUUID().toString().replace("-","");
		
//		System.out.println("文件新名称："+newName); 
		String today=DateUtil.getToday();
		//指定上传文件的目标目录为C:/upload
		//如果要获取src/main/resources目录下static/img目录的路径，可使用:
		//String realPath=ResourceUtils.getURL("classpath:static/img").getPath();
		String realPath=new String("src/main/resources/static/file/"+today);//request.getRealPath("/")+today;
		System.out.println(realPath);
		File folder=new File(realPath);
		if(!folder.exists()) //如果文件夹不存在，则创建文件夹，如果存在，不重复创建
			folder.mkdirs(); //创建文件夹
		String newName=UUID.randomUUID().toString().replace("-","")+".doc";
		String Path = new String(realPath+"/"+newName);
		try {
			pfile.transferTo(new File(folder,newName));
			url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+today+newName;
			System.out.println(url);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//返回上传的图片的路径，用于在页面上显示图片
		result.put("path", realPath);
		result.put("url", url);
		us.addResume(uid, jid, Path);
		
		return Path;
	}
	
	@GetMapping("/getbykeys")
	@ResponseBody
	public List<Map<String,Object>> getByKeys(@RequestParam(value="bpro",required = false)String bpro,
			@RequestParam(value="jeducation",required = false)String education,
			@RequestParam(value="jtime",required = false)String time
			,@RequestParam(value="jsalary",required = false)String salary) {
		//time=time+"天";
		System.out.println(education);
		System.out.println(time);
		System.out.println(salary);
		List<Map<String,Object>> jobs=us.queryJobByMult(bpro,education, time, salary);
		
		return jobs;
	}
	
	
	//l-
	@GetMapping("/getresume")
	@ResponseBody
	public List<Map<String,Object>> getresume(String uid){
		return us.getresumeByuid(uid);
	}
}
